package com.bluno.connection;

import java.util.UUID;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;


@TargetApi(7)
public class ConnManager {
	// Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_TOAST = 5;
    public static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    public static final String NAME = "Bluno";

    private int mState;
    private BluetoothAdapter btAdapter;
    private AcceptThread acceptThread;
    private ConnectThread connectThread;
    private ConnectedThread connectedThread;
    
    private Handler handler;
    
    public ConnManager(Handler handler)
    {
    	this.handler = handler;
    }
    
    public ConnectThread getConnectThread() {
    	return this.connectThread;
    }
    
    public void setConnectThread(ConnectThread connectThread) {
    	this.connectThread = connectThread;
    }
    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    public synchronized void setState(int state) {

        mState = state;
        System.out.println("SET STATE TO "+mState);
       // Give the new state to the Handler so the UI Activity can update
       //handler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    /**
     * Return the current connection state. */
    public synchronized int getState() {
	    System.out.println("GET STATE = "+mState);
        return mState;
    }
    
    public BluetoothAdapter getBtAdapter() {
		return btAdapter;
	}

	public void setBtAdapter(BluetoothAdapter btAdapter) {
		this.btAdapter = btAdapter;
	}

	/**
     * Start the ConnectThread to initiate a connection to a remote device.
     * @param device  The BluetoothDevice to connect
     */
    public synchronized void connect(BluetoothDevice device) {
        // Cancel any thread attempting to make a connection
        if (mState == STATE_CONNECTING) {
            if (connectThread != null) {connectThread.cancel(); connectThread = null;}
        }

        // Cancel any thread currently running a connection
        if (connectedThread != null) {connectedThread.cancel(); connectedThread = null;}

        // Start the thread to connect with the given device
        connectThread = new ConnectThread(this, device);
        connectThread.start();
        setState(STATE_CONNECTING);
    }
    
    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket) {
       
        // Cancel the thread that completed the connection
        if (connectThread != null) {connectThread.cancel(); connectThread = null;}

        // Cancel any thread currently running a connection
        if (connectedThread != null) {connectedThread.cancel(); connectedThread = null;}

        // Cancel the accept thread because we only want to connect to one device
        if (acceptThread != null) {acceptThread.cancel(); acceptThread = null;}

        // Start the thread to manage the connection and perform transmissions
        connectedThread = new ConnectedThread(this, socket);
        connectedThread.start();

//        // Send the name of the connected device back to the UI Activity
//        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
//        Bundle bundle = new Bundle();
//        bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
//        msg.setData(bundle);
//        mHandler.sendMessage(msg);

        setState(STATE_CONNECTED);
        
        System.out.println("CONECTOO "+socket.getRemoteDevice().getName());
		handler.obtainMessage(10)
        .sendToTarget();
    }
    
    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (connectThread != null) {connectThread.cancel(); connectThread = null;}
        if (connectedThread != null) {connectedThread.cancel(); connectedThread = null;}
        if (acceptThread != null) {acceptThread.cancel(); acceptThread = null;}
        setState(STATE_NONE);
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
    	 
        // Create temporary object
        ConnectedThread r;
       
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = connectedThread;
         
        }
        // Perform the write unsynchronized
        r.write(out);
       
    }

    public Handler getHandler()
    {
    	return handler;
    }
//    /**
//     * Indicate that the connection attempt failed and notify the UI Activity.
//     */
//    private void connectionFailed() {
//       
//    }
//
//    /**
//     * Indicate that the connection was lost and notify the UI Activity.
//     */
//    private void connectionLost() {
//  
//    }
}
